package com.shulidata.mock.controller.groovy;

import com.shulidata.mock.controller.BaseRestController;
import com.shulidata.mock.model.MockConf;
import com.shulidata.mock.service.MockConfService;
import com.shulidata.mock.service.groovy.GroovyManager;
import com.shulidata.mock.utils.GenericException;
import com.shulidata.mock.utils.Result;
import com.shulidata.mock.utils.ServiceCode;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author fyduan
 * @date 16/4/29
 */
@RestController
public class MockController extends BaseRestController {

    @Autowired
    private GroovyManager groovyManager;
    @Autowired
    private MockConfService confService;

    // 编辑mock接口配置
    @RequestMapping(value = "/mock/conf", method = RequestMethod.POST)
    public Result ctrlEditMockConf(MockConf mockConf) throws GenericException {
        MockConf _conf = confService.saveOrUpdate(mockConf);

        return new Result<MockConf>(ServiceCode.OK, _conf);
    }

    // 根据ID，删除单条记录
    @RequestMapping(value = "/mock/conf", method = RequestMethod.DELETE)
    public Result ctrlDeleteMockConf(@RequestParam("id") String id) {
        confService.deleteById(id);
        return new Result(ServiceCode.OK);
    }

    // 加载所有的mock配置数据
    @RequestMapping(value = "/mock/confs")
    public Result ctrlGetConfList() {
        List<MockConf> list = confService.loadAll();

        return new Result<List<MockConf>>(ServiceCode.OK, list);
    }

    // 根据ID获取MOCK配置记录
    @RequestMapping(value = "/mock/conf/info", method = RequestMethod.GET)
    public Result ctrlGetMockConfInfoById(@RequestParam("id") String id) {
        MockConf conf = confService.findById(id);
        if (conf == null || Strings.isBlank(conf.getId()) || Strings.isBlank(conf.getScriptMethod())) {
            return new Result(ServiceCode.ERR_PARAM, "没有找到 [ID:" + id + "] 对应的MOCK配置记录。");
        }

        return new Result<MockConf>(ServiceCode.OK, conf);
    }

}
